<html lang="en-US">

<head>
    
<title>「连载六」编写一个简单的文件日志 - 花落雨忧</title>

<meta property="og:title" content="「连载六」编写一个简单的文件日志 - 花落雨忧">



    



    
    <meta property="description" content="在上一节中，我们解决了 API&amp;rsquo;s 可以任意访问的问题，那么我们现在还有一个问题，就是我们的日志，都是输出到控制台上的，这显然对于一个项目来说是不合理的，因此我们这一节简单封装log库，使其支持简单的文件日志！
[&amp;hellip;] 我们在pkg下新建logging目录，新建file.go和log.go文件，写入内容：
[&amp;hellip;] 1、 file.go：
[&amp;hellip;] &amp;hellip;">
    <meta property="og:description" content="在上一节中，我们解决了 API&amp;rsquo;s 可以任意访问的问题，那么我们现在还有一个问题，就是我们的日志，都是输出到控制台上的，这显然对于一个项目来说是不合理的，因此我们这一节简单封装log库，使其支持简单的文件日志！
[&amp;hellip;] 我们在pkg下新建logging目录，新建file.go和log.go文件，写入内容：
[&amp;hellip;] 1、 file.go：
[&amp;hellip;] &amp;hellip;">
    






<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1">

<link rel="shortcut icon" href="https://www.lican.asia/logo/logo.png" type="image/x-icon" />



<link rel="stylesheet" href="/css/style.min.css" />

<link rel="stylesheet" href="/css/reset.min.css" />




<script src="https://www.lican.asia/js/highlight.min.js"></script>

<script>
hljs.configure({ ignoreUnescapedHTML: true })
hljs.highlightAll();
</script>


<script src="https://www.lican.asia/js/jquery.min.js"></script>




<link href="https://www.lican.asia/css/hugo-code.min.css" rel="stylesheet" />



    <style>
        .post-content img {
            max-width: 400px;
        }
    </style>
</head>

<body id="period" class="home blog">
    <a class="skip-content" href="#main">Press "Enter" to skip to content</a>
    <div id="overflow-container" class="overflow-container">
        <header class="site-header" id="site-header" role="banner">
    <div class="max-width">
        <div id="title-container" class="title-container">
            <div id="site-title" class="site-title"><a href="/">花落雨忧</a></div>
            <p class="tagline">思所及 力所行 方为真.</p>
        </div>
        
        <div id="menu-primary-container" class="menu-primary-container">
            <div class="icon-container">
            </div>
            <div id="menu-primary" class="menu-container menu-primary" role="navigation">
                <nav class="menu">
                    <ul id="menu-primary-items" class="menu-primary-items">
                        
                        
                        <li id="menu-item-0"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/posts" aria-current="page" tabindex="0">首页</a></li>
                        
                        <li id="menu-item-1"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/tech/" aria-current="page" tabindex="1">技术文档</a></li>
                        
                        <li id="menu-item-2"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/article/" aria-current="page" tabindex="2">文章</a></li>
                        
                        <li id="menu-item-3"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/project/" aria-current="page" tabindex="3">项目</a></li>
                        
                        <li id="menu-item-4"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/about/" aria-current="page" tabindex="4">关于</a></li>
                        
                    </ul>
                </nav>
            </div>
        </div>
    </div>
</header>

        <div id="primary-container" class="primary-container">
            <div class="max-width">
                <section id="main" class="main" role="main">
                    <div id="loop-container" class="loop-container">
                        <div
                            class="post type-post status-publish format-standard hentry entry">
                            <article>
                                <div class="post-container">
                                    <div class="post-header">
                                        <h2 class="post-title">
                                            <a href="/posts/posts/go/gin/2018-02-15-log/">「连载六」编写一个简单的文件日志</a>
                                        </h2>
                                        
                                        <div class="post-byline">Published on
                                            <a class="date" href="javascript:;">2018/02/15</a>
                                            
                                            
                                            
                                            By 
                                            <a class="author" href="javascript:;">煎鱼</a></div>
                                            
                                        
                                    </div>
                                    <div class="post-content">
                                        <h2 id="涉及知识点">涉及知识点</h2>
<ul>
<li>自定义 log。</li>
</ul>
<h2 id="本文目标">本文目标</h2>
<p>在上一节中，我们解决了 API&rsquo;s 可以任意访问的问题，那么我们现在还有一个问题，就是我们的日志，都是输出到控制台上的，这显然对于一个项目来说是不合理的，因此我们这一节简单封装<code>log</code>库，使其支持简单的文件日志！</p>
<h2 id="新建logging包">新建<code>logging</code>包</h2>
<p>我们在<code>pkg</code>下新建<code>logging</code>目录，新建<code>file.go</code>和<code>log.go</code>文件，写入内容：</p>
<h3 id="编写file文件">编写<code>file</code>文件</h3>
<p><strong>1、 file.go：</strong></p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#f92672">package</span> <span style="color:#a6e22e">logging</span>
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#f92672">import</span> (
</span></span><span style="display:flex;"><span>	<span style="color:#e6db74">&#34;os&#34;</span>
</span></span><span style="display:flex;"><span>	<span style="color:#e6db74">&#34;time&#34;</span>
</span></span><span style="display:flex;"><span>	<span style="color:#e6db74">&#34;fmt&#34;</span>
</span></span><span style="display:flex;"><span>	<span style="color:#e6db74">&#34;log&#34;</span>
</span></span><span style="display:flex;"><span>)
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">var</span> (
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">LogSavePath</span> = <span style="color:#e6db74">&#34;runtime/logs/&#34;</span>
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">LogSaveName</span> = <span style="color:#e6db74">&#34;log&#34;</span>
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">LogFileExt</span> = <span style="color:#e6db74">&#34;log&#34;</span>
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">TimeFormat</span> = <span style="color:#e6db74">&#34;20060102&#34;</span>
</span></span><span style="display:flex;"><span>)
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">func</span> <span style="color:#a6e22e">getLogFilePath</span>() <span style="color:#66d9ef">string</span> {
</span></span><span style="display:flex;"><span>	<span style="color:#66d9ef">return</span> <span style="color:#a6e22e">fmt</span>.<span style="color:#a6e22e">Sprintf</span>(<span style="color:#e6db74">&#34;%s&#34;</span>, <span style="color:#a6e22e">LogSavePath</span>)
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">func</span> <span style="color:#a6e22e">getLogFileFullPath</span>() <span style="color:#66d9ef">string</span> {
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">prefixPath</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">getLogFilePath</span>()
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">suffixPath</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">fmt</span>.<span style="color:#a6e22e">Sprintf</span>(<span style="color:#e6db74">&#34;%s%s.%s&#34;</span>, <span style="color:#a6e22e">LogSaveName</span>, <span style="color:#a6e22e">time</span>.<span style="color:#a6e22e">Now</span>().<span style="color:#a6e22e">Format</span>(<span style="color:#a6e22e">TimeFormat</span>), <span style="color:#a6e22e">LogFileExt</span>)
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>	<span style="color:#66d9ef">return</span> <span style="color:#a6e22e">fmt</span>.<span style="color:#a6e22e">Sprintf</span>(<span style="color:#e6db74">&#34;%s%s&#34;</span>, <span style="color:#a6e22e">prefixPath</span>, <span style="color:#a6e22e">suffixPath</span>)
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">func</span> <span style="color:#a6e22e">openLogFile</span>(<span style="color:#a6e22e">filePath</span> <span style="color:#66d9ef">string</span>) <span style="color:#f92672">*</span><span style="color:#a6e22e">os</span>.<span style="color:#a6e22e">File</span> {
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">_</span>, <span style="color:#a6e22e">err</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">os</span>.<span style="color:#a6e22e">Stat</span>(<span style="color:#a6e22e">filePath</span>)
</span></span><span style="display:flex;"><span>	<span style="color:#66d9ef">switch</span> {
</span></span><span style="display:flex;"><span>		<span style="color:#66d9ef">case</span> <span style="color:#a6e22e">os</span>.<span style="color:#a6e22e">IsNotExist</span>(<span style="color:#a6e22e">err</span>):
</span></span><span style="display:flex;"><span>			<span style="color:#a6e22e">mkDir</span>()
</span></span><span style="display:flex;"><span>		<span style="color:#66d9ef">case</span> <span style="color:#a6e22e">os</span>.<span style="color:#a6e22e">IsPermission</span>(<span style="color:#a6e22e">err</span>):
</span></span><span style="display:flex;"><span>			<span style="color:#a6e22e">log</span>.<span style="color:#a6e22e">Fatalf</span>(<span style="color:#e6db74">&#34;Permission :%v&#34;</span>, <span style="color:#a6e22e">err</span>)
</span></span><span style="display:flex;"><span>	}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">handle</span>, <span style="color:#a6e22e">err</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">os</span>.<span style="color:#a6e22e">OpenFile</span>(<span style="color:#a6e22e">filePath</span>, <span style="color:#a6e22e">os</span>.<span style="color:#a6e22e">O_APPEND</span> | <span style="color:#a6e22e">os</span>.<span style="color:#a6e22e">O_CREATE</span> | <span style="color:#a6e22e">os</span>.<span style="color:#a6e22e">O_WRONLY</span>, <span style="color:#ae81ff">0644</span>)
</span></span><span style="display:flex;"><span>	<span style="color:#66d9ef">if</span> <span style="color:#a6e22e">err</span> <span style="color:#f92672">!=</span> <span style="color:#66d9ef">nil</span> {
</span></span><span style="display:flex;"><span>		<span style="color:#a6e22e">log</span>.<span style="color:#a6e22e">Fatalf</span>(<span style="color:#e6db74">&#34;Fail to OpenFile :%v&#34;</span>, <span style="color:#a6e22e">err</span>)
</span></span><span style="display:flex;"><span>	}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>	<span style="color:#66d9ef">return</span> <span style="color:#a6e22e">handle</span>
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">func</span> <span style="color:#a6e22e">mkDir</span>() {
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">dir</span>, <span style="color:#a6e22e">_</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">os</span>.<span style="color:#a6e22e">Getwd</span>()
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">err</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">os</span>.<span style="color:#a6e22e">MkdirAll</span>(<span style="color:#a6e22e">dir</span> <span style="color:#f92672">+</span> <span style="color:#e6db74">&#34;/&#34;</span> <span style="color:#f92672">+</span> <span style="color:#a6e22e">getLogFilePath</span>(), <span style="color:#a6e22e">os</span>.<span style="color:#a6e22e">ModePerm</span>)
</span></span><span style="display:flex;"><span>	<span style="color:#66d9ef">if</span> <span style="color:#a6e22e">err</span> <span style="color:#f92672">!=</span> <span style="color:#66d9ef">nil</span> {
</span></span><span style="display:flex;"><span>		panic(<span style="color:#a6e22e">err</span>)
</span></span><span style="display:flex;"><span>	}
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><ul>
<li><code>os.Stat</code>：返回文件信息结构描述文件。如果出现错误，会返回<code>*PathError</code></li>
</ul>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#66d9ef">type</span> <span style="color:#a6e22e">PathError</span> <span style="color:#66d9ef">struct</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">Op</span>   <span style="color:#66d9ef">string</span>
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">Path</span> <span style="color:#66d9ef">string</span>
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">Err</span>  <span style="color:#66d9ef">error</span>
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><ul>
<li><code>os.IsNotExist</code>：能够接受<code>ErrNotExist</code>、<code>syscall</code>的一些错误，它会返回一个布尔值，能够得知文件不存在或目录不存在</li>
<li><code>os.IsPermission</code>：能够接受<code>ErrPermission</code>、<code>syscall</code>的一些错误，它会返回一个布尔值，能够得知权限是否满足</li>
<li><code>os.OpenFile</code>：调用文件，支持传入文件名称、指定的模式调用文件、文件权限，返回的文件的方法可以用于 I/O。如果出现错误，则为<code>*PathError</code>。</li>
</ul>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#66d9ef">const</span> (
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// Exactly one of O_RDONLY, O_WRONLY, or O_RDWR must be specified.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    <span style="color:#a6e22e">O_RDONLY</span> <span style="color:#66d9ef">int</span> = <span style="color:#a6e22e">syscall</span>.<span style="color:#a6e22e">O_RDONLY</span> <span style="color:#75715e">// 以只读模式打开文件
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    <span style="color:#a6e22e">O_WRONLY</span> <span style="color:#66d9ef">int</span> = <span style="color:#a6e22e">syscall</span>.<span style="color:#a6e22e">O_WRONLY</span> <span style="color:#75715e">// 以只写模式打开文件
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    <span style="color:#a6e22e">O_RDWR</span>   <span style="color:#66d9ef">int</span> = <span style="color:#a6e22e">syscall</span>.<span style="color:#a6e22e">O_RDWR</span>   <span style="color:#75715e">// 以读写模式打开文件
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    <span style="color:#75715e">// The remaining values may be or&#39;ed in to control behavior.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    <span style="color:#a6e22e">O_APPEND</span> <span style="color:#66d9ef">int</span> = <span style="color:#a6e22e">syscall</span>.<span style="color:#a6e22e">O_APPEND</span> <span style="color:#75715e">// 在写入时将数据追加到文件中
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    <span style="color:#a6e22e">O_CREATE</span> <span style="color:#66d9ef">int</span> = <span style="color:#a6e22e">syscall</span>.<span style="color:#a6e22e">O_CREAT</span>  <span style="color:#75715e">// 如果不存在，则创建一个新文件
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    <span style="color:#a6e22e">O_EXCL</span>   <span style="color:#66d9ef">int</span> = <span style="color:#a6e22e">syscall</span>.<span style="color:#a6e22e">O_EXCL</span>   <span style="color:#75715e">// 使用O_CREATE时，文件必须不存在
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    <span style="color:#a6e22e">O_SYNC</span>   <span style="color:#66d9ef">int</span> = <span style="color:#a6e22e">syscall</span>.<span style="color:#a6e22e">O_SYNC</span>   <span style="color:#75715e">// 同步IO
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    <span style="color:#a6e22e">O_TRUNC</span>  <span style="color:#66d9ef">int</span> = <span style="color:#a6e22e">syscall</span>.<span style="color:#a6e22e">O_TRUNC</span>  <span style="color:#75715e">// 如果可以，打开时
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>)
</span></span></code></pre></div><ul>
<li><code>os.Getwd</code>：返回与当前目录对应的根路径名</li>
<li><code>os.MkdirAll</code>：创建对应的目录以及所需的子目录，若成功则返回<code>nil</code>，否则返回<code>error</code></li>
<li><code>os.ModePerm</code>：<code>const</code>定义<code>ModePerm FileMode = 0777</code></li>
</ul>
<h3 id="编写log文件">编写<code>log</code>文件</h3>
<p><strong>2、log.go</strong></p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#f92672">package</span> <span style="color:#a6e22e">logging</span>
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#f92672">import</span> (
</span></span><span style="display:flex;"><span>	<span style="color:#e6db74">&#34;log&#34;</span>
</span></span><span style="display:flex;"><span>	<span style="color:#e6db74">&#34;os&#34;</span>
</span></span><span style="display:flex;"><span>	<span style="color:#e6db74">&#34;runtime&#34;</span>
</span></span><span style="display:flex;"><span>	<span style="color:#e6db74">&#34;path/filepath&#34;</span>
</span></span><span style="display:flex;"><span>	<span style="color:#e6db74">&#34;fmt&#34;</span>
</span></span><span style="display:flex;"><span>)
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">type</span> <span style="color:#a6e22e">Level</span> <span style="color:#66d9ef">int</span>
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">var</span> (
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">F</span> <span style="color:#f92672">*</span><span style="color:#a6e22e">os</span>.<span style="color:#a6e22e">File</span>
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">DefaultPrefix</span> = <span style="color:#e6db74">&#34;&#34;</span>
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">DefaultCallerDepth</span> = <span style="color:#ae81ff">2</span>
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">logger</span> <span style="color:#f92672">*</span><span style="color:#a6e22e">log</span>.<span style="color:#a6e22e">Logger</span>
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">logPrefix</span> = <span style="color:#e6db74">&#34;&#34;</span>
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">levelFlags</span> = []<span style="color:#66d9ef">string</span>{<span style="color:#e6db74">&#34;DEBUG&#34;</span>, <span style="color:#e6db74">&#34;INFO&#34;</span>, <span style="color:#e6db74">&#34;WARN&#34;</span>, <span style="color:#e6db74">&#34;ERROR&#34;</span>, <span style="color:#e6db74">&#34;FATAL&#34;</span>}
</span></span><span style="display:flex;"><span>)
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">const</span> (
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">DEBUG</span> <span style="color:#a6e22e">Level</span> = <span style="color:#66d9ef">iota</span>
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">INFO</span>
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">WARNING</span>
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">ERROR</span>
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">FATAL</span>
</span></span><span style="display:flex;"><span>)
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">func</span> <span style="color:#a6e22e">init</span>() {
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">filePath</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">getLogFileFullPath</span>()
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">F</span> = <span style="color:#a6e22e">openLogFile</span>(<span style="color:#a6e22e">filePath</span>)
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">logger</span> = <span style="color:#a6e22e">log</span>.<span style="color:#a6e22e">New</span>(<span style="color:#a6e22e">F</span>, <span style="color:#a6e22e">DefaultPrefix</span>, <span style="color:#a6e22e">log</span>.<span style="color:#a6e22e">LstdFlags</span>)
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">func</span> <span style="color:#a6e22e">Debug</span>(<span style="color:#a6e22e">v</span> <span style="color:#f92672">...</span><span style="color:#66d9ef">interface</span>{}) {
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">setPrefix</span>(<span style="color:#a6e22e">DEBUG</span>)
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">logger</span>.<span style="color:#a6e22e">Println</span>(<span style="color:#a6e22e">v</span>)
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">func</span> <span style="color:#a6e22e">Info</span>(<span style="color:#a6e22e">v</span> <span style="color:#f92672">...</span><span style="color:#66d9ef">interface</span>{}) {
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">setPrefix</span>(<span style="color:#a6e22e">INFO</span>)
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">logger</span>.<span style="color:#a6e22e">Println</span>(<span style="color:#a6e22e">v</span>)
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">func</span> <span style="color:#a6e22e">Warn</span>(<span style="color:#a6e22e">v</span> <span style="color:#f92672">...</span><span style="color:#66d9ef">interface</span>{}) {
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">setPrefix</span>(<span style="color:#a6e22e">WARNING</span>)
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">logger</span>.<span style="color:#a6e22e">Println</span>(<span style="color:#a6e22e">v</span>)
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">func</span> <span style="color:#a6e22e">Error</span>(<span style="color:#a6e22e">v</span> <span style="color:#f92672">...</span><span style="color:#66d9ef">interface</span>{}) {
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">setPrefix</span>(<span style="color:#a6e22e">ERROR</span>)
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">logger</span>.<span style="color:#a6e22e">Println</span>(<span style="color:#a6e22e">v</span>)
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">func</span> <span style="color:#a6e22e">Fatal</span>(<span style="color:#a6e22e">v</span> <span style="color:#f92672">...</span><span style="color:#66d9ef">interface</span>{}) {
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">setPrefix</span>(<span style="color:#a6e22e">FATAL</span>)
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">logger</span>.<span style="color:#a6e22e">Fatalln</span>(<span style="color:#a6e22e">v</span>)
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">func</span> <span style="color:#a6e22e">setPrefix</span>(<span style="color:#a6e22e">level</span> <span style="color:#a6e22e">Level</span>) {
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">_</span>, <span style="color:#a6e22e">file</span>, <span style="color:#a6e22e">line</span>, <span style="color:#a6e22e">ok</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">runtime</span>.<span style="color:#a6e22e">Caller</span>(<span style="color:#a6e22e">DefaultCallerDepth</span>)
</span></span><span style="display:flex;"><span>	<span style="color:#66d9ef">if</span> <span style="color:#a6e22e">ok</span> {
</span></span><span style="display:flex;"><span>		<span style="color:#a6e22e">logPrefix</span> = <span style="color:#a6e22e">fmt</span>.<span style="color:#a6e22e">Sprintf</span>(<span style="color:#e6db74">&#34;[%s][%s:%d]&#34;</span>, <span style="color:#a6e22e">levelFlags</span>[<span style="color:#a6e22e">level</span>], <span style="color:#a6e22e">filepath</span>.<span style="color:#a6e22e">Base</span>(<span style="color:#a6e22e">file</span>), <span style="color:#a6e22e">line</span>)
</span></span><span style="display:flex;"><span>	} <span style="color:#66d9ef">else</span> {
</span></span><span style="display:flex;"><span>		<span style="color:#a6e22e">logPrefix</span> = <span style="color:#a6e22e">fmt</span>.<span style="color:#a6e22e">Sprintf</span>(<span style="color:#e6db74">&#34;[%s]&#34;</span>, <span style="color:#a6e22e">levelFlags</span>[<span style="color:#a6e22e">level</span>])
</span></span><span style="display:flex;"><span>	}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">logger</span>.<span style="color:#a6e22e">SetPrefix</span>(<span style="color:#a6e22e">logPrefix</span>)
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><ul>
<li><code>log.New</code>：创建一个新的日志记录器。<code>out</code>定义要写入日志数据的<code>IO</code>句柄。<code>prefix</code>定义每个生成的日志行的开头。<code>flag</code>定义了日志记录属性</li>
</ul>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#66d9ef">func</span> <span style="color:#a6e22e">New</span>(<span style="color:#a6e22e">out</span> <span style="color:#a6e22e">io</span>.<span style="color:#a6e22e">Writer</span>, <span style="color:#a6e22e">prefix</span> <span style="color:#66d9ef">string</span>, <span style="color:#a6e22e">flag</span> <span style="color:#66d9ef">int</span>) <span style="color:#f92672">*</span><span style="color:#a6e22e">Logger</span> {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">return</span> <span style="color:#f92672">&amp;</span><span style="color:#a6e22e">Logger</span>{<span style="color:#a6e22e">out</span>: <span style="color:#a6e22e">out</span>, <span style="color:#a6e22e">prefix</span>: <span style="color:#a6e22e">prefix</span>, <span style="color:#a6e22e">flag</span>: <span style="color:#a6e22e">flag</span>}
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><ul>
<li><code>log.LstdFlags</code>：日志记录的格式属性之一，其余的选项如下</li>
</ul>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#66d9ef">const</span> (
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">Ldate</span>         = <span style="color:#ae81ff">1</span> <span style="color:#f92672">&lt;&lt;</span> <span style="color:#66d9ef">iota</span>     <span style="color:#75715e">// the date in the local time zone: 2009/01/23
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    <span style="color:#a6e22e">Ltime</span>                         <span style="color:#75715e">// the time in the local time zone: 01:23:23
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    <span style="color:#a6e22e">Lmicroseconds</span>                 <span style="color:#75715e">// microsecond resolution: 01:23:23.123123.  assumes Ltime.
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    <span style="color:#a6e22e">Llongfile</span>                     <span style="color:#75715e">// full file name and line number: /a/b/c/d.go:23
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    <span style="color:#a6e22e">Lshortfile</span>                    <span style="color:#75715e">// final file name element and line number: d.go:23. overrides Llongfile
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    <span style="color:#a6e22e">LUTC</span>                          <span style="color:#75715e">// if Ldate or Ltime is set, use UTC rather than the local time zone
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>    <span style="color:#a6e22e">LstdFlags</span>     = <span style="color:#a6e22e">Ldate</span> | <span style="color:#a6e22e">Ltime</span> <span style="color:#75715e">// initial values for the standard logger
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>)
</span></span></code></pre></div><p>当前目录结构：</p>
<pre tabindex="0"><code>gin-blog/
├── conf
│   └── app.ini
├── main.go
├── middleware
│   └── jwt
│       └── jwt.go
├── models
│   ├── article.go
│   ├── auth.go
│   ├── models.go
│   └── tag.go
├── pkg
│   ├── e
│   │   ├── code.go
│   │   └── msg.go
│   ├── logging
│   │   ├── file.go
│   │   └── log.go
│   ├── setting
│   │   └── setting.go
│   └── util
│       ├── jwt.go
│       └── pagination.go
├── routers
│   ├── api
│   │   ├── auth.go
│   │   └── v1
│   │       ├── article.go
│   │       └── tag.go
│   └── router.go
├── runtime
</code></pre><p>我们自定义的<code>logging</code>包，已经基本完成了，接下来让它接入到我们的项目之中吧。我们打开先前包含<code>log</code>包的代码，如下：</p>
<ol>
<li>打开<code>routers</code>目录下的<code>article.go</code>、<code>tag.go</code>、<code>auth.go</code>。</li>
<li>将<code>log</code>包的引用删除，修改引用我们自己的日志包为<code>github.com/EDDYCJY/go-gin-example/pkg/logging</code>。</li>
<li>将原本的<code>log.Println(...)</code>改为<code>logging.Info(...)</code>。</li>
</ol>
<p>例如<code>auth.go</code>文件的修改内容：</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#f92672">package</span> <span style="color:#a6e22e">api</span>
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#f92672">import</span> (
</span></span><span style="display:flex;"><span>	<span style="color:#e6db74">&#34;net/http&#34;</span>
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>	<span style="color:#e6db74">&#34;github.com/gin-gonic/gin&#34;</span>
</span></span><span style="display:flex;"><span>	<span style="color:#e6db74">&#34;github.com/astaxie/beego/validation&#34;</span>
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>	<span style="color:#e6db74">&#34;github.com/EDDYCJY/go-gin-example/pkg/e&#34;</span>
</span></span><span style="display:flex;"><span>	<span style="color:#e6db74">&#34;github.com/EDDYCJY/go-gin-example/pkg/util&#34;</span>
</span></span><span style="display:flex;"><span>	<span style="color:#e6db74">&#34;github.com/EDDYCJY/go-gin-example/models&#34;</span>
</span></span><span style="display:flex;"><span>	<span style="color:#e6db74">&#34;github.com/EDDYCJY/go-gin-example/pkg/logging&#34;</span>
</span></span><span style="display:flex;"><span>)
</span></span><span style="display:flex;"><span><span style="color:#f92672">...</span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">func</span> <span style="color:#a6e22e">GetAuth</span>(<span style="color:#a6e22e">c</span> <span style="color:#f92672">*</span><span style="color:#a6e22e">gin</span>.<span style="color:#a6e22e">Context</span>) {
</span></span><span style="display:flex;"><span>	<span style="color:#f92672">...</span>
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">code</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">e</span>.<span style="color:#a6e22e">INVALID_PARAMS</span>
</span></span><span style="display:flex;"><span>	<span style="color:#66d9ef">if</span> <span style="color:#a6e22e">ok</span> {
</span></span><span style="display:flex;"><span>		<span style="color:#f92672">...</span>
</span></span><span style="display:flex;"><span>	} <span style="color:#66d9ef">else</span> {
</span></span><span style="display:flex;"><span>	    <span style="color:#66d9ef">for</span> <span style="color:#a6e22e">_</span>, <span style="color:#a6e22e">err</span> <span style="color:#f92672">:=</span> <span style="color:#66d9ef">range</span> <span style="color:#a6e22e">valid</span>.<span style="color:#a6e22e">Errors</span> {
</span></span><span style="display:flex;"><span>                <span style="color:#a6e22e">logging</span>.<span style="color:#a6e22e">Info</span>(<span style="color:#a6e22e">err</span>.<span style="color:#a6e22e">Key</span>, <span style="color:#a6e22e">err</span>.<span style="color:#a6e22e">Message</span>)
</span></span><span style="display:flex;"><span>            }
</span></span><span style="display:flex;"><span>	}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">c</span>.<span style="color:#a6e22e">JSON</span>(<span style="color:#a6e22e">http</span>.<span style="color:#a6e22e">StatusOK</span>, <span style="color:#a6e22e">gin</span>.<span style="color:#a6e22e">H</span>{
</span></span><span style="display:flex;"><span>        <span style="color:#e6db74">&#34;code&#34;</span> : <span style="color:#a6e22e">code</span>,
</span></span><span style="display:flex;"><span>        <span style="color:#e6db74">&#34;msg&#34;</span> : <span style="color:#a6e22e">e</span>.<span style="color:#a6e22e">GetMsg</span>(<span style="color:#a6e22e">code</span>),
</span></span><span style="display:flex;"><span>        <span style="color:#e6db74">&#34;data&#34;</span> : <span style="color:#a6e22e">data</span>,
</span></span><span style="display:flex;"><span>    })
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><h2 id="验证功能">验证功能</h2>
<p>修改文件后，重启服务，我们来试试吧！</p>
<p>获取到 API 的 Token 后，我们故意传错误 URL 参数给接口，如：<code>http://127.0.0.1:8000/api/v1/articles?tag_id=0&amp;state=9999999&amp;token=eyJhbG..</code></p>
<p>然后我们到<code>$GOPATH/gin-blog/runtime/logs</code>查看日志：</p>
<pre tabindex="0"><code>$ tail -f log20180216.log
[INFO][article.go:79]2018/02/16 18:33:12 [state 状态只允许0或1]
[INFO][article.go:79]2018/02/16 18:33:42 [state 状态只允许0或1]
[INFO][article.go:79]2018/02/16 18:33:42 [tag_id 标签ID必须大于0]
[INFO][article.go:79]2018/02/16 18:38:39 [state 状态只允许0或1]
[INFO][article.go:79]2018/02/16 18:38:39 [tag_id 标签ID必须大于0]
</code></pre><p>日志结构一切正常，我们的记录模式都为<code>Info</code>，因此前缀是对的，并且我们是入参有问题，也把错误记录下来了，这样排错就很方便了！</p>
<p>至此，本节就完成了，这只是一个简单的扩展，实际上我们线上项目要使用的文件日志，是更复杂一些，开动你的大脑 举一反三吧！</p>
<h2 id="参考">参考</h2>
<h3 id="本系列示例代码">本系列示例代码</h3>
<ul>
<li><a href="https://github.com/EDDYCJY/go-gin-example">go-gin-example</a></li>
</ul>
<h2 id="关于">关于</h2>
<h3 id="修改记录">修改记录</h3>
<ul>
<li>第一版：2018 年 02 月 16 日发布文章</li>
<li>第二版：2019 年 10 月 01 日修改文章</li>
</ul>
<h2 id="heading">？</h2>
<p>如果有任何疑问或错误，欢迎在 <a href="https://github.com/EDDYCJY/blog">issues</a> 进行提问或给予修正意见，如果喜欢或对你有所帮助，欢迎 Star，对作者是一种鼓励和推进。</p>
<h3 id="我的公众号">我的公众号</h3>
<p><img src="https://image.eddycjy.com/8d0b0c3a11e74efd5fdfd7910257e70b.jpg" alt="image"></p>


                                        
                                        
                                        
                                        <div class="rp4wp-related-posts">
                                            <h3>相关文章</h3>
                                            <ul>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.asia/posts/posts/go/gin/2018-02-14-jwt/">「连载五」使用 JWT 进行身份校验</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.asia/posts/posts/go/gin/2018-02-13-api-03/">「连载四」Gin搭建Blog API&#39;s （三）</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.asia/posts/posts/go/gin/2018-02-12-api-02/">「连载三」Gin搭建Blog API&#39;s （二）</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.asia/posts/posts/go/gin/2018-02-11-api-01/">「连载二」Gin搭建Blog API&#39;s （一）</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.asia/posts/posts/go/gin/2018-02-10-install/">「连载一」Go 介绍与环境安装</a>
                                                    </div>
                                                </li>
                                                
                                            </ul>
                                        </div>
                                        
                                        
                                    </div>

                                    
                                    
                                    

                                    
                                    <div class="post-meta">
                                        
                                        
                                        <div class="post-tags">
                                            <ul>
                                            
                                            <li>
                                                <a href="/tags/go" title="View all posts tagged match">go</a>
                                            </li>
                                            
                                            <li>
                                                <a href="/tags/gin" title="View all posts tagged match">gin</a>
                                            </li>
                                            
                                            </ul>
                                        </div>
                                        
                                        
                                        <nav class="further-reading">
                                            
                                            <div class="previous">
                                                <span>&lt;&lt; Prev</span>
                                                <a href="https://www.lican.asia/posts/posts/go/gin/2018-02-14-jwt/"
                                                    rel="prev">「连载五」使用 JWT 进行身份校验</a> </div>
                                            
                                            
                                            <div class="next">
                                                <span>Next >></span>
                                                <a href="https://www.lican.asia/posts/posts/go/grpc-gateway/2018-02-23-install/">「连载一」gRPC介绍与环境安装</a> 
                                            </div>
                                            
                                        </nav>
                                    </div>
                                    
                                    

                                    
                                    
                                    

                                </div>
                            </article>
                        </div>
                    </div>
                </section>
                <aside class="sidebar sidebar-primary" id="sidebar-primary" role="complementary">
    <h1 class="screen-reader-text">Sidebar</h1>
    

    
    
    <section id="text-2" class="widget widget_text">
        <div class="textwidget">
            
            <div id="profile">
                <div id="profile_picture"><img src="https://www.lican.asia/logo/logo.png"></div>
                <div id="profile_intro">
                    <p><span class="name">Lican</span></p>
                    <p class="intro">全栈开发者，爱好造轮子。</p>
                </div>
            </div>
            
            <p>
                <script type="text/javascript">
                    (function ($) {
                        $(document).ready(function () {
                            var menuPrimaryContainer = $('#menu-primary-container');
                            var profile = $('#text-2');
                            $('#toggle-navigation').click(function () {
                                if (menuPrimaryContainer.hasClass('open')) {
                                    profile.removeClass('open');
                                } else {
                                    profile.addClass('open');
                                }
                            });
                        });
                    })(jQuery);
                </script>
            </p>
        </div>
    </section>
    
    
    
    
    
    <section id="text-5" class="widget widget_text">
        <h2 class="widget-title">开源项目</h2>
        <div class="textwidget">
            <div id="projects" style="line-height: 22px;">
                
                <a href="https://github.com/idoubi/gonews"
                    target="_blank">gonews</a>: &nbsp;Daily news for golang<br>
                
                <a href="https://github.com/idoubi/sql2struct"
                    target="_blank">sql2struct</a>: &nbsp;Generate go struct according to SQL<br>
                
                <a href="https://github.com/idoubi/goz"
                    target="_blank">goz</a>: &nbsp;Request library used in golang<br>
                
        </div>
    </section>
    
    

    
    
    
    
    <section id="qrcode" class="widget widget_media_image">
        <h2 class="widget-title">微信公众号</h2>
        <img width="258" height="258"
            src="https://www.lican.asia/wechat/lican.png"
            class="image wp-image-5514  attachment-full size-full" alt=""
            style="max-width: 100%; height: auto;"
            sizes="(max-width: 258px) 100vw, 258px">
    </section>
    
    

    
    
    

    
    
    

    
    
    
    
</aside>
            </div>
        </div>

        <footer id="site-footer" class="site-footer" role="contentinfo">
    <div class="max-width">
    </div>
    <div class="footer">
        <div id="footercontent">
            © lican.asia All rights reserved<br/>
            Built with Hugo Theme <a href="https://github.com/idoubi/hugo-theme-period" target="_blank">Period</a>
        </div>
    </div>
</footer>

<script>
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?e8351b6d4626d5881d439ea1f6184baa";
      var s = document.getElementsByTagName("script")[0]; 
      s.parentNode.insertBefore(hm, s);
    })();
</script>
    
    
    </div>
    
</body>

</html>